<?php

use com\gdl\kq\dataobject\adminstatistics\AdminStatisticsDTO;
use com\gdl\common\dataobject\common\ResultDO;
use com\gdl\kq\interfaces\AttAdminStatisticsServiceIf;
/**
 *  考勤
 *  @author gdl
 */
class api_AttAdminStatisticsService extends api_Abstract implements AttAdminStatisticsServiceIf
{
    //统计接口
    public function statisticsAdminUserParticularInfos(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $unitId    = $data['unitId']?$data['unitId']:0;
        $agId    = $data['agId']?$data['agId']:0;
        $unitIds    = $data['unitIds']?$data['unitIds']:0;
        $memberIds = $data['memberIds']?$data['memberIds']:0;
        $offset    = $data['offset']?$data['offset']:0;
        $num       = $data['num']?$data['num']:10;
        $date       = $data['date']?$data['date']:0;
        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}
        if(empty($adminUserId)){$result->message = "参数不正确"; return $result;}

        try{
            $userStatisticsInfos = [];
            $memberModel            = new model_attendance_member();
            $attendancerecordModel  = new model_attendance_attendancerecord();
            $attendancegroupModel   = new model_attendance_attendancegroup();
            $serviceUserModel       = new service_user();
            $serviceGlobalsModel    = new service_globals();
            $groupmemberrecordModel    = new model_attendance_groupmemberrecord();
            $approvalprocessleaverecordModel    = new model_attendance_approvalprocessleaverecord();

            //获取当前平台的组织架构和考勤用户的关联数组
            $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);

            if ($UnitsList){
                $UnitsList = $serviceGlobalsModel->setArrKeyId($UnitsList['relation']);
            }
//            print_r(json_encode($UnitsList));die;
            //查询该平台下所有人员
            $memberleftJoin = array('atdc_position as `ap`' => '`ap`.id=atdc_member.positionId');
            if($agId){
                $memberleftJoin = array(
                    'atdc_position as `ap`' => '`ap`.id=atdc_member.positionId',
                    'atdc_attendance_group_user as `aau`' => '`aau`.memberId=atdc_member.id',
                );
            }

            $memberCondition = " atdc_member.platformId = {$platformId} and atdc_member.status=2 ";
            if ($memberIds){
                $memberCondition .= " and atdc_member.id in ($memberIds) ";
            }
            if ($agId){
                $memberCondition .= " and aau.agId = {$agId} and aau.status=0 ";
            }
            if ($unitIds){
                if (is_array($unitIds)){
                    $unitIds = implode(',',$unitIds);
                }
                $memberCondition .= " and atdc_member.unitId in ($unitIds) ";
            }
            #分页
            if($offset=='0') $offset=1;
            $limit = ($offset - 1) * $num . "," . $num;
            $group = 'order by atdc_member.id desc limit '.$limit;

            $userLists = $memberModel->select(
                $memberCondition,
                'atdc_member.*,ap.title positionName',
                $group,
                '',
                $memberleftJoin
            )->items;

            $count = $memberModel->selectOne(
                $memberCondition,
                'count(*) num',
                "",
                '',
                $memberleftJoin
            );
            $count = $count?$count['num']:0;
            if ($userLists){
                $arrayDate = [];
                //传递日期是否为空
                if (empty($date)){//获取当月数据
                    $startDateTime = date('Y-m-01',time());  //获取本月第一天日期
                    $endDateTime   = date('Y-m-d', strtotime("$startDateTime +1 month -1 day"));//获取本月最后一天日期
                    $beginThismonth = mktime(0,0,0,date('m'),1,date('Y'));
                    $endThismonth   = mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $datetime1 = date_create($startDateTime);
                    $datetime2 = date_create($endDateTime);
                    $interval = date_diff($datetime1, $datetime2);

                    $dateNum = $interval->format('%a')+1;

                    for($i=0;$i<$dateNum;$i++) {
                        $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                    }
                }else{
                    $date = explode(' ',$date);
                    $startDateTime = $date[0];
                    $endDateTime = $date[1];
                    if ($startDateTime==$endDateTime){
                        $beginThismonth = strtotime($startDateTime);
                        $endThismonth = $beginThismonth;
                        $dateNum = 1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }else{
                        $beginThismonth = strtotime($startDateTime);
                        $endThismonth = strtotime($endDateTime)+16*60*60-1;
                        $datetime1 = date_create($startDateTime);
                        $datetime2 = date_create($endDateTime);
                        $interval = date_diff($datetime1, $datetime2);
                        $dateNum = $interval->format('%a')+1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }

                }

                //根据userid获取所有的考勤记录
                $userids = array_column($userLists,'id');
                $userids = implode(',',$userids);
                $attendancerecordCondition = "no<>2 and memberId in ($userids) and isDelete=0 and UNIX_TIMESTAMP(sureDate)>={$beginThismonth} and UNIX_TIMESTAMP(sureDate)<={$endThismonth}";
                $attendancerecordLists = $attendancerecordModel->select($attendancerecordCondition)->items;
                if ($attendancerecordLists){
                    $attendancerecordList = [];
                    foreach ($attendancerecordLists as $arLK=>$arlV){
                        $attendancerecordList[$arlV['memberId']][$arlV['sureDate']][] =  [
                            'id'=>$arlV['id'],
                            'leaveIn'=>$arlV['leaveIn'],
                            'leaveInId'=>$arlV['leaveInId'],
                            'no'=>$arlV['no'],
                            'clockinType'=>$arlV['clockinType'],
                            'clockinNum'=>$arlV['clockinNum'],
                            'clockinTime'=>$arlV['clockinTime'],
                        ];
                    }
                }else{
                    $attendancerecordList = [];
                }

                    //查询出平台下所有考勤组
//                    $attendancegroupList = $attendancegroupModel->select(" isDelete= 0 and platformId={$platformId}")->items;
//                    if ($attendancegroupList)$attendancegroupList = $serviceGlobalsModel->setArrKeyId($attendancegroupList);
                //考勤组权限限制
                $attendancegroup = "  atdc_attendance_group.isDelete= 0 and atdc_attendance_group.platformId={$platformId} ";//and aagu.type=1 and aagu.type<>2
                $appadminuser = new model_lhbase_appadminuser();
                $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
                if (!$appadminuserInfo){
                    $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
                    $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

                    if ($attendancegroupIds){
                        $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                        $attendancegroupIds = implode(',',$attendancegroupIds);
                        $attendancegroup .= " and atdc_attendance_group.id in ({$attendancegroupIds}) ";
                    }else{
                        $result->message = "暂无数据";
                        $result->code = 200;
                        $result->data = [];
                        $result->counts = 0;
                        return $result;
                    }
                }

                    $userAttendancegroupJoin = array('atdc_attendance_group_user as aagu' => 'aagu.agId=atdc_attendance_group.id');
                    $userAttendancegroupList = $attendancegroupModel->select(
                        $attendancegroup,
                        'aagu.memberId id,aagu.agId,atdc_attendance_group.title,atdc_attendance_group.id agId',
                        '',
                        '',
                        $userAttendancegroupJoin
                    )->items;
                    if ($userAttendancegroupList)$userAttendancegroupList = $serviceGlobalsModel->setArrKeyId($userAttendancegroupList);

                    foreach ($userLists as $key=>$valus){
                        $userStatisticsInfos[$valus['id']]['id'] = $valus['id'];
                        $userStatisticsInfos[$valus['id']]['realName'] = $valus['realName'];
                        $userStatisticsInfos[$valus['id']]['positionName'] = $valus['positionName'];
                        $userStatisticsInfos[$valus['id']]['unitsName'] = isset($UnitsList[$valus['unitId']])?$UnitsList[$valus['unitId']]['title']:"";//@@
                        $userStatisticsInfos[$valus['id']]['upLevelNnitsName'] = (isset($UnitsList[$valus['unitId']]) && isset($UnitsList[$UnitsList[$valus['unitId']]['pid']]))?$UnitsList[$UnitsList[$valus['unitId']]['pid']]['title']:"本单位";
                        $userStatisticsInfos[$valus['id']]['attendanceGroupName'] = isset($userAttendancegroupList[$valus['id']])?$userAttendancegroupList[$valus['id']]['title']:"未添加考勤组";//@@
                        $userClockinList = isset($attendancerecordList[$valus['id']])?$attendancerecordList[$valus['id']]:'';

                        $userDateList = [];
                        //组装数据
                        foreach ($arrayDate as $dateKey=>$dateValue){
                            $startDateNowTime = strtotime($dateValue." 00:00:00");
                            $endDateNowTime = strtotime($dateValue." 23:59:59");
                            $undate = strtotime($dateValue);
                            //查询用户当天是否需要打卡 考勤组人员档案表 根据档案表查询历史配置
                            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("FIND_IN_SET('{$valus['id']}',memberIds) and addTime<={$endDateNowTime} order by id  desc");
//                            if ($dateValue=="2018-08-20"){
//
//                                print_r($groupmemberrecordModel);die;
//                            }
                            if ($groupmemberrecordInfo){
                                $workdayKey = unserialize($groupmemberrecordInfo['workday']);

                                $holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
                                //特殊工作日定义 [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
                                $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));

                                //获取日期是否是休息日 bool false是节假日  true不是节假日
                                $isHolidaysAndFestivals = $serviceGlobalsModel->getDateIsHolidaysAndFestivals($dateValue,$workdayKey,$holidayKey,$specialWorkdayKey);

                                //查询用户当天是否有请假记录
                                $leaverecordList = $approvalprocessleaverecordModel->select(" memberId = {$valus['id']} and status= 2 and startTime>$startDateNowTime and endTime<$endDateNowTime")->items;

                                if ($leaverecordList){
                                    $leaveDate = [];
                                    $leaverecordType = array("事假","年假","事假","调休","产假","婚假","丧假");
                                    foreach ($leaverecordList as $leaverecordK=>$leaverecordV){
                                        $leaveDate[] = $leaverecordType[$leaverecordV['leaveType']]."从".date('Y-m-d H:i',$leaverecordV['startTime'])."到".date('Y-m-d H:i',$leaverecordV['endTime']);
                                    }
                                    $leaveDate = implode(',',$leaveDate);
                                }else{
                                    $leaveDate = "";
                                }
                                $upTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $downTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];

                                if (isset($userClockinList[$dateValue])){
                                    foreach ($userClockinList[$dateValue] as $clockinV){
                                        if ($clockinV['clockinType']==1 && $clockinV['clockinNum']==1){
                                            $upTime[1] = date("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==1){
                                            $downTime[1] = date("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==2){
                                            $upTime[2] = date("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==2){
                                            $downTime[2] = date("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==3){
                                            $upTime[3] = date("H:i",$clockinV['clockinTime']);
                                        }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==3){
                                            $downTime[3] = date("H:i",$clockinV['clockinTime']);
                                        }
                                    }
                                    $userDateList[$dateValue] = [
                                        'status'=>$isHolidaysAndFestivals?1:2,//1正常 2休息
                                        'upTime'=>$upTime,
                                        'downTime'=>$downTime,
                                        'leaveDate'=>$leaveDate,
                                    ];
                                }
                                else{
                                    $upTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                    $downTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                    $leaveDate = "";
                                    $userDateList[$dateValue] = [
                                        'status'=>$isHolidaysAndFestivals?1:2,//1正常 2休息
                                        'upTime'=>$upTime,
                                        'downTime'=>$downTime,
                                        'leaveDate'=>$leaveDate,
                                    ];
                                }
                            }
                            else{
                                $isHolidaysAndFestivals = 1;
                                $upTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $downTime = [1=>'未打卡',2=>'未打卡',3=>'未打卡'];
                                $leaveDate = "";
                                $userDateList[$dateValue] = [
                                    'status'=>$isHolidaysAndFestivals?1:2,//1正常 2休息
                                    'upTime'=>$upTime,
                                    'downTime'=>$downTime,
                                    'leaveDate'=>$leaveDate,
                                ];
                            }

                        }

                        //二次组装
                        $dateMod = [];
                        $upTime = [];
                        $downTime = [];
                        $leaveDate = [];
                        $weekarray = array("日","一","二","三","四","五","六"); //先定义一个数组
                        foreach ($userDateList as $ke=>$valu){
                            $dateMod[] = $ke."/星期".$weekarray[date("w",strtotime($ke))];
                            if ($valu['status']==2){
                                foreach ($valu['upTime'] as $kk=>$vv){
                                    if ($vv=='未打卡'){
                                        $upTime[] = [$ke,'休息中'];
                                    }else{
                                        $upTime[] = [$ke,$vv];
                                    }
                                }
                                foreach ($valu['downTime'] as $kk=>$vv){
                                    if ($vv=='未打卡'){
                                        $downTime[] = [$ke,'休息中'];
                                    }else{
                                        $downTime[] = [$ke,$vv];
                                    }
                                }
//                                $upTime[] = [$ke,'休息中'];
//                                $upTime[] = [$ke,'休息中'];
//                                $upTime[] = [$ke,'休息中'];
//                                $downTime[] = [$ke,'休息中'];
//                                $downTime[] = [$ke,'休息中'];
//                                $downTime[] = [$ke,'休息中'];
                            }else{
                                foreach ($valu['upTime'] as $kk=>$vv){
                                    $upTime[] = [$ke,$vv];
                                }
                                foreach ($valu['downTime'] as $kk=>$vv){
                                    $downTime[] = [$ke,$vv];
                                }
                            }
                            $leaveDate[] = [$ke,$valu['leaveDate']];
                        }


//                        $arrayDate = $arrayDate;
                        $userStatisticsInfos[$valus['id']]['dateMod'] = $dateMod;
                        $userStatisticsInfos[$valus['id']]['upTime'] = $upTime;
                        $userStatisticsInfos[$valus['id']]['downTime'] = $downTime;
                        $userStatisticsInfos[$valus['id']]['leaveDate'] = $leaveDate;
//                        $userStatisticsInfos[$valus['id']]['dateList'] = $userDateList;
//                        print_r(json_encode($dateMod));die;

                    }
//                    print_r(json_encode($userStatisticsInfos));die;
                $result->data = [[json_encode($userStatisticsInfos)]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }else{
                $result->data = [[]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }
        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }

    //通过日期获取人员打卡详细
    public function getAdminUserClockinRecordByDate(AdminStatisticsDTO $AdminStatisticsDTO){
        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) : "";

        #接受参数

        $date = $data['date']?$data['date']:0;
        $userId = $data['userId']?$data['userId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($userId)){$result->message = "请选择用户"; return $result;}
        if(empty($date)){$result->message = "请选择日期"; return $result;}

        try{
            $attendancerecordModel = new model_attendance_attendancerecord();
            $groupmemberrecordModel = new model_attendance_groupmemberrecord();
            $attendancegroupModel = new model_attendance_attendancegroup();
            $serviceGlobalsModel = new service_globals();
            $undate = strtotime($date);
            $tTime = $undate+86399;
            //查询用户当天是否需要打卡 考勤组人员档案表 根据档案表查询历史配置
            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("FIND_IN_SET('{$userId}',memberIds) and addTime<={$tTime} order by id  desc");
            if ($groupmemberrecordInfo) {
                $goDaysNum = unserialize($groupmemberrecordInfo['goDaysNum']);
                $num = count($goDaysNum);
            }else{
                $num = 0;
            }
            $returnList = [
                [
                ],[
                ],[
                ],[
                ],[
                ],[]
//                [
//                    'clockinSureTime'=>'',
//                    'clockinTime'=>'',
//                    'type'=>"无记录",
////                    'address'=>'',
//                    'remark'=>'',
//                    'title'=>'',
//                    'coordinate'=>[],
//                    'deviation'=>'',
//                    'photo'=>'',
//                    'coordinateR'=>[]
//                ]
            ];
            switch ($num){
                case 0:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    unset($returnList[3]);
                    unset($returnList[2]);
                    unset($returnList[1]);
                    unset($returnList[0]);
                    break;
                case 1:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    unset($returnList[3]);
                    unset($returnList[2]);
                    break;
                case 2:
                    unset($returnList[5]);
                    unset($returnList[4]);
                    break;
            }
            $userrecordList  = $attendancerecordModel->select(" memberId = {$userId} and sureDate= '{$date}' and isDelete = 0")->items;
            $violation = new model_attendance_violation();
            foreach ($userrecordList as $clockinV){
                $type = "正常";
                if ($clockinV['abnormal']==1){//1 迟到 2 早退
                    $type = "迟到";
                }elseif ($clockinV['abnormal']==2){//1 迟到 2 早退
                    $type = "早退";
                }
                if ($clockinV['absenteeism']>=1){
                    $type = "旷工";
                }
                //1正常打卡 2缺卡 3补卡
                if ($clockinV['no']==2 || $clockinV['no']==3){//这个班次缺卡了或已经补卡
                    $type = $clockinV['no']==3?"补卡":"缺卡";
                }
                if ($clockinV['isGo']==2){//1正常考勤 2外勤打卡
                    $type .= ",外勤";
                }
                if ($clockinV['leaveIn']==2){//这个班次请假了
                    $type = "请假";
                }
                $address = !empty($clockinV['clockinCoordinate'])?unserialize($clockinV['clockinCoordinate']):'';
                $coordinateR = !empty($clockinV['coordinate'])?unserialize($clockinV['coordinate']):'';
                //获取当次人脸识别照片
                $photo = $violation->selectOne(
                    " id= {$clockinV['vioLationId']} "
                );
                if (!$photo){
                    $photo = $violation->selectOne(
                        " agId={$clockinV['agId']} and memberId={$clockinV['memberId']} and clockinNum={$clockinV['clockinNum']} and clockinType={$clockinV['clockinType']}"
                    );
                }
                $data = [
                    'clockinSureTime'=>$clockinV['sureTime'],
                    'clockinTime'=>!empty($clockinV['clockinTime'])?date('Y-m-d H:i:s',$clockinV['clockinTime']):'',
                    'type'=>$type,
//                    'address'=>$address,
                    'remark'=>!empty($clockinV['remark'])?$clockinV['remark']:'',
                    'photo'=>!empty($photo['currentImg'])?$photo['currentImg']:'',
                    'title'=>!empty($address)?$serviceGlobalsModel->format_html($address['title']):'',
                    'deviation'=>!empty($address)?$address['deviation']:'',
                    'coordinate'=>!empty($address)?($address['Childcoordinate']?$address['Childcoordinate']:$address['coordinate']):'',
                    'coordinateR'=>!empty($coordinateR)?$coordinateR:'',
                ];
                if ($clockinV['clockinType']==1 && $clockinV['clockinNum']==1){
                    $returnList[0] = $data;
                }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==1){
                    $returnList[1] = $data;
                }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==2){
                    $returnList[2] = $data;
                }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==2){
                    $returnList[3] = $data;
                }elseif ($clockinV['clockinType']==1 && $clockinV['clockinNum']==3){
                    $returnList[4] = $data;
                }elseif ($clockinV['clockinType']==2 && $clockinV['clockinNum']==3){
                    $returnList[5] = $data;
                }
            }
            $serviceGlobalsModel = new service_globals();
            $returnList = $serviceGlobalsModel->filter_array($returnList,[[]]);
            $result->data = [[json_encode($returnList)]];
            $result->message ='成功';
            $result->code = 200;

        }catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //统计平台下的考勤接口
    public function getStatisticsPlatformClockin(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $date = $data['date']?$data['date']:0;
        $unitId    = $data['unitId']?$data['unitId']:0;
        $unitIds    = $data['unitIds']?$data['unitIds']:0;
        $agId    = $data['agId']?$data['agId']:0;
        $memberIds = $data['memberIds']?$data['memberIds']:0;
        $offset    = $data['offset']?$data['offset']:0;
        $num       = $data['num']?$data['num']:10;
        $adminUserId       = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($platformId)){$result->message = "请选择平台"; return $result;}

        try{
            $recordings =  [
                'daysNum'=>0,//工作日天数
                'clockinNum'=>0,//考勤正常天数
                'late'=>0, //迟到
                'leavEarly'=>0,//早退
                'completion'=>0,//旷工 累计旷工时长
                'overtime'=>0,//旷工 累计旷工时长
                'upMissCard'=>0,//上班缺卡次数
                'downMissCard'=>0,//下班缺卡次数
                'field'=>0,//外勤天数
                'leave'=>0,//请假
                'YearLeave'=>0,//年假
                'casualLeave'=>0,//事假
                'restLeave'=>0,//调休
                'restRotateLeave'=>0,//轮休
                'maternityLeave'=>0,//产假
                'maritalLeave'=>0,//婚假
                'funeralLeave'=>0,//丧假
                'nursingLeave'=>0,//护理假
                'sickLeave'=>0,//病假
            ];
            $userStatisticsInfos = [];
            $memberModel            = new model_attendance_member();
            $attendancerecordModel  = new model_attendance_attendancerecord();
            $attendancegroupModel   = new model_attendance_attendancegroup();
            $serviceUserModel       = new service_user();
            $serviceGlobalsModel    = new service_globals();
            $groupmemberrecordModel    = new model_attendance_groupmemberrecord();
            $approvalprocessleaverecordModel    = new model_attendance_approvalprocessleaverecord();

            //获取当前平台的组织架构和考勤用户的关联数组
            $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);

            if ($UnitsList){
                $UnitsList = $serviceGlobalsModel->setArrKeyId($UnitsList['relation']);
            }
//            print_r(json_encode($UnitsList));die;
            //查询该平台下所有人员
            $memberleftJoin = array(
                'atdc_position as `ap`' => '`ap`.id=atdc_member.positionId'
            );
            if($agId){
                $memberleftJoin = array(
                    'atdc_position as `ap`' => '`ap`.id=atdc_member.positionId',
                    'atdc_attendance_group_user as `aau`' => '`aau`.memberId=atdc_member.id',
                );
            }
            $memberCondition = " atdc_member.platformId = {$platformId} and atdc_member.status=2 ";
            if ($memberIds){
                $memberCondition .= " and atdc_member.id in ($memberIds) ";
            }
            if ($agId){
                $memberCondition .= " and aau.agId = {$agId} and aau.status=0 ";
            }
            if ($unitIds){
                if (is_array($unitIds)){
                    $unitIds = implode(',',$unitIds);
                }
                $memberCondition .= " and atdc_member.unitId in ($unitIds) ";
            }
            #分页
            if($offset=='0') $offset=1;
            $limit = ($offset - 1) * $num . "," . $num;
            $group = 'order by atdc_member.id desc limit '.$limit;

            $userLists = $memberModel->select(
                $memberCondition,
                'atdc_member.*,ap.title positionName',
                $group,
                '',
                $memberleftJoin
            )->items;

            $count = $memberModel->selectOne(
                $memberCondition,
                'count(*) num',
                "",
                '',
                $memberleftJoin
            );
            $count = $count?$count['num']:0;
            if ($userLists){
                $arrayDate = [];
                //传递日期是否为空
                if (empty($date)){//获取当月数据
                    $startDateTime = date('Y-m-01',time());  //获取本月第一天日期
                    $endDateTime   = date('Y-m-d', strtotime("$startDateTime +1 month -1 day"));//获取本月最后一天日期
                    $beginThismonth = mktime(0,0,0,date('m'),1,date('Y'));
                    $endThismonth   = mktime(23,59,59,date('m'),date('t'),date('Y'));
                    $datetime1 = date_create($startDateTime);
                    $datetime2 = date_create($endDateTime);
                    $interval = date_diff($datetime1, $datetime2);

                    $dateNum = $interval->format('%a')+1;

                    for($i=0;$i<$dateNum;$i++) {
                        $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                    }
                }else{
                    $date = explode(' ',urldecode($date));
                    $startDateTime = $date[0];
                    $endDateTime = $date[1];
                    if ($startDateTime==$endDateTime){
                        $beginThismonth = strtotime($startDateTime." 00:00:00");
                        $endThismonth = strtotime($startDateTime." 23:59:59");
                        $dateNum = 1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }else{
                        $beginThismonth = strtotime($startDateTime." 00:00:00");
                        $endThismonth = strtotime($endDateTime)+16*60*60-1;
                        $datetime1 = date_create($startDateTime);
                        $datetime2 = date_create($endDateTime);
                        $interval = date_diff($datetime1, $datetime2);
                        $dateNum = $interval->format('%a')+1;
                        for($i=0;$i<$dateNum;$i++) {
                            $arrayDate[] = date('Y-m-d',$beginThismonth+$i*86400); //每隔一天赋值给数组
                        }
                    }

                }

                //根据userid获取所有的考勤记录
                $userids = array_column($userLists,'id');
                $userids = implode(',',$userids);
                $attendancerecordCondition = " memberId in ($userids) and isDelete=0 and UNIX_TIMESTAMP(sureDate)>={$beginThismonth} and UNIX_TIMESTAMP(sureDate)<={$endThismonth}";
                $attendancerecordLists = $attendancerecordModel->select($attendancerecordCondition)->items;
                if ($attendancerecordLists){
                    $attendancerecordList = [];
                    foreach ($attendancerecordLists as $arLK=>$arlV){
                        $attendancerecordList[$arlV['memberId']][$arlV['sureDate']][] =  [
                            'id'=>$arlV['id'],
                            'leaveIn'=>$arlV['leaveIn'],
                            'leaveInId'=>$arlV['leaveInId'],
                            'no'=>$arlV['no'],
                            'clockinType'=>$arlV['clockinType'],
                            'clockinNum'=>$arlV['clockinNum'],
                            'clockinTime'=>$arlV['clockinTime'],
                        ];
                    }
                }else{
                    $attendancerecordList = [];
                }
                $attendancegroup = " isDelete= 0 and atdc_attendance_group.platformId={$platformId}";
                $appadminuser = new model_lhbase_appadminuser();
                $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
//        print_r($adminUserId);die;
                if (!$appadminuserInfo){
                    $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
                    $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

                    if ($attendancegroupIds){
                        $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                        $attendancegroupIds = implode(',',$attendancegroupIds);
                        $attendancegroup .= " and atdc_attendance_group.id in ({$attendancegroupIds}) ";
                    }else{
                        $result->message = "暂无数据";
                        $result->code = 200;
                        $result->data = [];
                        $result->counts = 0;
                        return $result;
                    }
                }
                //查询出平台下所有考勤组
                $attendancegroupList = $attendancegroupModel->select($attendancegroup)->items;
                if ($attendancegroupList)$attendancegroupList = $serviceGlobalsModel->setArrKeyId($attendancegroupList);
                $userAttendancegroupJoin = array('atdc_attendance_group_user as aagu' => 'aagu.agId=atdc_attendance_group.id');
                $userAttendancegroupList = $attendancegroupModel->select(
                    "  atdc_attendance_group.isDelete= 0 and atdc_attendance_group.platformId={$platformId} and aagu.type=1 and aagu.type<>2",
                    'aagu.memberId id,aagu.agId,atdc_attendance_group.title,atdc_attendance_group.id agId',
                    '',
                    '',
                    $userAttendancegroupJoin
                )->items;
                if ($userAttendancegroupList)$userAttendancegroupList = $serviceGlobalsModel->setArrKeyId($userAttendancegroupList);

                $attendancerecord = new model_attendance_attendancerecord();
                $overtimerecord = new model_attendance_overtimerecord();
                $leaverecordModel = new model_attendance_approvalprocessleaverecord();
                $replacementrecordModel = new model_attendance_approvalprocesscardreplacementrecord();
                if ($arrayDate){
                    $arrayDate = implode("','",$arrayDate);
                    $arrayDate = "'".$arrayDate."'";
                }else{
                    $arrayDate = 1;
                }
                foreach ($userLists as $key=>$valus){
                    $userStatisticsInfos[$valus['id']]['id'] = $valus['id'];
                    $userStatisticsInfos[$valus['id']]['realName'] = $valus['realName'];
                    $userStatisticsInfos[$valus['id']]['positionName'] = $valus['positionName'];
                    $userStatisticsInfos[$valus['id']]['unitsName'] = isset($UnitsList[$valus['unitId']])?$UnitsList[$valus['unitId']]['title']:"";//@@
                    $userStatisticsInfos[$valus['id']]['upLevelNnitsName'] = (isset($UnitsList[$valus['unitId']]) && isset($UnitsList[$UnitsList[$valus['unitId']]['pid']]))?$UnitsList[$UnitsList[$valus['unitId']]['pid']]['title']:"本单位";
                    $userStatisticsInfos[$valus['id']]['attendanceGroupName'] = isset($userAttendancegroupList[$valus['id']])?$userAttendancegroupList[$valus['id']]['title']:"未添加考勤组";//@@

                    $condition ="memberId = {$valus['id']} and sureDate in ({$arrayDate}) ";
                    $field = "sum(if((no=2 && clockinType=1 && notClockin=1 && isRest=1 && leaveIn=1 ),1,0)) as upMissCard,sum(if((no=2 && clockinType=2 && notClockin=1 && isRest=1 && leaveIn=1 ),1,0)) as downMissCard,sum(if(leaveIn=2,1,0)) as `leave`,sum(if((abnormalIdentityIs=2 or abnormalCoordinateIs=2),1,0)) as abnormal,sum(if(abnormal=1 && notClockin=1 && isRest=1 && leaveIn=1 ,1,0)) as late,sum(if(abnormal=2 && notClockin=1 && isRest=1 && leaveIn=1 ,1,0)) as leavEarly,sum(if(absenteeism>=1 && notClockin=1 && isRest=1 && leaveIn=1 ,1,0)) as completion,sum(if(overtimeIs=2 && notClockin=1 && isRest=1 && leaveIn=1 ,1,0)) as overtime";
                    $lists = $attendancerecord->selectOne($condition,$field);
                    foreach ($recordings as $key=>$value){
                        $onTimeList = [];
                        $daysNum = $dateNum;
                        if ($key=="onTime"){//
                            $onTimeList =  $attendancerecord->select(
                                " memberId = {$valus['id']} and sureDate in ({$arrayDate}) and absenteeism=2 and abnormal=0 and no=1 and leaveIn=1 and notClockin=1 and isRest=1 ",
                                "id,sureDate,sureTime,count(id) num"
                            )->items;
                            $recordings['onTime'] = $onTimeList?$onTimeList[0]['num']:0;
                        }
                        elseif ($key=="daysNum"){
                            $undate = strtotime($endDateTime)+86400;
                            //根据用户ID获取考勤天数
                            $groupmemberrecordInfo = $groupmemberrecordModel->selectOne("FIND_IN_SET('{$valus['id']}',memberIds) and addTime<={$undate} order by id  desc");

                            if (!$groupmemberrecordInfo){//当天没有班次添加
                                $recordings['daysNum'] = 0;
                            }else {
//                                $dateNum 选择日期总天数
                                $workdayKey = unserialize($groupmemberrecordInfo['workday']);
                                $holidayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['holiday']));
                                $specialWorkdayKey = $this->arrayDateToKey(unserialize($groupmemberrecordInfo['specialWorkday']));
                                $arrayDateX = explode(',',$arrayDate);
                                foreach ($arrayDateX as $dK=>$dV){
                                    $dV = str_replace("'",'',$dV);
                                    $dVw = strtotime($dV);
                                    $wDate = date('w',$dVw);
                                    if ($wDate==0){
                                        $wDate=7;
                                    }
                                    if (in_array($wDate,$workdayKey)){//选择的日期为工作日 正常情况下需要打卡
                                        //判断当天是否为节假日
                                        if (in_array($dV,$holidayKey)){//是节假日不需要打卡
                                            $daysNum = $daysNum-1;//节假日
                                        }
                                    }else{//休息日 本身不需要打卡 但是有特殊工作日时需求打卡
                                        $daysNum = $daysNum-1;//节假日
                                        if (in_array($dV,$specialWorkdayKey)){//选择日期为特殊工作日
                                            $daysNum = $daysNum+1;//特殊工作日
                                        }
                                    }
                                }
                                $recordings['daysNum'] = $daysNum;
                            }
                        }
                        elseif ($key=="completion"){
                            $completion = 0;
                            $completionList =$attendancerecord->select(
                                "memberId = {$valus['id']} and sureDate in ({$arrayDate}) and absenteeism>=1 and notClockin=1 and isRest=1 and leaveIn=1","id,memberId,clockinTime,sureTime,sureDate,clockinType")->items;

                            foreach ($completionList as $completionK=>$completionV){
                                if ($completionV['clockinType']==1){//1上班打卡 2下班打卡
                                    $completion += $completionV['clockinTime']-strtotime($completionV['sureDate']." ".$completionV['sureTime']);
                                }else{
                                    $completion += strtotime($completionV['sureDate']." ".$completionV['sureTime'])-$completionV['clockinTime'];
                                }
                            }
                            $completion = $completion>0?$serviceGlobalsModel->secsToStrws($completion):0;
                            $recordings['completion'] = $completion;
                        }elseif ($key=="overtime"){
                            $overtime = 0;
                            //获取时间段内的加班时段
                            $overtimeList =$overtimerecord->select(
                                " memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2","id,numbers")->items;
                            if ($valus['id']==89){
                               // print_r($overtimerecord);die;
                            }
                            if ($overtimeList){
                                $overtime = array_column($overtimeList,'numbers');
                                $overtime = array_sum($overtime);
                                $overtime = $overtime*3600;
                                $overtime = $overtime>0?$serviceGlobalsModel->secsToStrws($overtime):0;
                            }
                            $recordings['overtime'] = $overtime;
                        }
                        elseif ($key=="field"){
                            $fieldS = 0;
                            $fieldLists =$attendancerecord->select(
                                "memberId = {$valus['id']} and sureDate in ({$arrayDate}) and isGo=2","id,sureDate")->items;
                            if ($fieldLists)$fieldS = count(array_unique(array_column($fieldLists,'sureDate')));
                            $recordings['field'] = $fieldS;
                        }
                        elseif ($key=="clockinNum"){
//                            $onTimeList =  $attendancerecord->select(
//                                " memberId = {$valus['id']} and sureDate in ({$arrayDate}) and absenteeism=0 and abnormal=0 and (no=1 || (no=3 && absenteeism=0 and abnormal=0))  or leaveIn=1  or isGo=2",
//                                "id,sureDate",
//                                "group by sureDate"
//                            )->items;
//                            $clockinNum = $onTimeList?count(array_column($onTimeList,'sureDate')):0;
////                            $clockinNum = $onTimeList?$onTimeList[0]['num']:0;
                            $recordings['clockinNum'] = 0;
                        }
                        elseif ($key=="leave" || $key=="YearLeave" || $key=="sickLeave" || $key=="nursingLeave" || $key=="casualLeave" || $key=="restLeave" || $key=="restRotateLeave" || $key=="maternityLeave" || $key=="maritalLeave" || $key=="funeralLeave" ){
                            $leaveTypes = array("事假","年假","事假","调休","产假","婚假","丧假","护理假","病假");
//                            请假类型 默认为0 1年假 2事假 3调休 4产假 5婚假 6丧假 7护理假 8病假
//'YearLeave' 年假 'casualLeave' 事假 'restLeave' 调休 maternityLeave' 产假  'maritalLeave' 婚假 'funeralLeave' 丧假
                                switch ($key){
                                    case "YearLeave":
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 1 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['YearLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//年假
                                        break;
                                    case 'casualLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 2 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['casualLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//事假
                                        break;
                                    case "restLeave"://调休
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 3 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['restLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//调休
                                        break;
                                    case 'maternityLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 4 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['maternityLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//产假
                                        break;
                                    case 'maritalLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 5 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['maritalLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//婚假
                                        break;
                                    case 'funeralLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 6 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['funeralLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//丧假
                                        break;
                                    case 'nursingLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 7 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['nursingLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//护理假
                                        break;
                                    case 'sickLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 8 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['sickLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//病
                                        break;
                                    case 'restRotateLeave':
                                        $onTimeList =  $leaverecordModel->selectOne(
                                            "leaveType = 9 and memberId = {$valus['id']} and startTime>$beginThismonth and endTime<$endThismonth and status=2",
                                            "id,count(*) num"
                                        );
                                        $recordings['restRotateLeave'] = !empty($onTimeList['num'])?$onTimeList['num']:0;//病
                                        break;
                                }
                        }
                        else
                        {
                            $recordings[$key] = $lists[$key]?$lists[$key]:0;
                        }
                    }
                    $userStatisticsInfos[$valus['id']]['recordings'] = $recordings;//@@
                }
//                    print_r(json_encode($userStatisticsInfos));die;
                $result->data = [[json_encode($userStatisticsInfos)]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }else{
                $result->data = [[]];
                $result->message ='成功';
                $result->code = 200;
                $result->counts = $count;
            }

        }
        catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //首页概况统计
    public function getStatisticsPlatformGeneral(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数
        $adminReg   = $data['adminReg']?$data['adminReg']:0;
        $adminUserId       = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        if(empty($platformId)){$result->message = "请选择平台"; return $result;}

        try{
            $pdata = [
                'CompanyUserNum'=>0,
                'groupNum'=>0,
                'unitNum'=>0
            ];
            $attendancegroupModel = new model_attendance_attendancegroup();
            $memberModel = new model_attendance_member();
            $unitsModel = new model_lhbase_units();
            //统计平台公司人数
            $CompanyUserNum = $memberModel->selectOne(" platformId={$platformId} and status=2","count(id) num");
            $pdata['CompanyUserNum']  = $CompanyUserNum?$CompanyUserNum['num']:0;
            //统计考勤组数量
            $groupNum = $attendancegroupModel->selectOne(" platformId={$platformId} and isDelete=0","count(id) num");
            $pdata['groupNum']  = $groupNum?$groupNum['num']:0;
            //统计平台公司人数
            $unitNum = $unitsModel->selectOne(" platformId={$platformId} and isDelete=1 and status=1","count(id) num");
            $pdata['unitNum']  = $unitNum?$unitNum['num']:0;
            $result->data = [$pdata];
            $result->message ='成功';
            $result->code = 200;

        }
        catch(Exception $e){
            $result->message = '异常';
        }

        return $result;
    }

    //array [2018-02-11?@(春节(补))','2018-02-11?@(清明节(补))','2018-02-11?@(春节(补))']
    private function arrayDateToKey($array){
        if (!is_array($array))return [];
        $dateArray = [];
        foreach ($array as $key=>$value){
            $dates = explode('?@',$value);
            $dateArray[] =$dates[0];
        }
        return $dateArray;
    }


    public function getFaceInfoNum(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        try{
            $userStatisticsInfos = [];
            $violationModel            = new model_attendance_violation();
            $num = $violationModel->selectOne("platformId = {$platformId}","count(id) num");

            $num = $num?$num['num']:0;
            $result->data = [[$num]];
            $result->message ='成功';
            $result->code = 200;
        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }

    /**
     * 首页考勤异常统计
     * $typesof  time=>按时间统计  company=>按项目统计
     * $days seven=>7天  week=>1周 month=>1个月 day=>自定义时间
     * @param AdminStatisticsDTO $AdminStatisticsDTO
     * @return ResultDO
     */
    public function getStatisticsUnusual(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数
        $globals = new service_globals();
        $adminUserId = $data['adminUserId']?$data['adminUserId'] : 0;
        $adminReg = $data['adminReg']?$globals->getStr($data['adminReg']): '';
//        $id = $data['id']?$globals->getStr($data['id']) : 0;
        //seven=>7天  week=>1周 month=>1个月 day=>自定义时间
        $dayse = $data['days']?$globals->getStr($data['days']) : 0;//
        $typesof = $data['typesof']?$globals->getStr($data['typesof']) : 'time';//
        $datime = $data['datime']?explode(',', $data['datime']):date('Y');//
        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        $field = 'count(atdc_attendance_record.id) nums';
        $condition = ' leaveIn<>2 and (no>1 or abnormalCoordinateIs=2 or abnormalIdentityIs<>1 or abnormal>=1) and isRest<>2  ';
        $attendancegroup = new model_attendance_attendancegroup();
        //考勤组权限限制
        $appadminuser = new model_lhbase_appadminuser();
        $appadminuserInfo = $appadminuser->selectOne("id={$adminUserId} and characters='zg' and unitsId=0");
        if (!$appadminuserInfo){
            $adminUserIdgroupId = new model_attendance_adminuserattendancegroup();
            $attendancegroupIds = $adminUserIdgroupId->select(" adminUserId = {$adminUserId} ",'attendancegroupId')->items;

            if ($attendancegroupIds){
                $attendancegroupIds = array_column($attendancegroupIds,'attendancegroupId');
                $attendancegroupIds = implode(',',$attendancegroupIds);
                $condition .= " and atdc_attendance_record.agId in ({$attendancegroupIds}) ";
            }else{
                $condition .= " and atdc_attendance_record.agId in (0) ";
            }
        }else{
            $attendancegroupIds = $attendancegroup->select(" platformId= {$platformId} and isDelete=0 and type=1",'id')->items;
            if ($attendancegroupIds){
                $attendancegroupIds = array_column($attendancegroupIds,'id');
                $attendancegroupIds = implode(',',$attendancegroupIds);
            }else{
                $attendancegroupIds = 0;
            }
            $condition .= "  and atdc_attendance_record.agId in ({$attendancegroupIds})  ";
        }

        $group = ' group by ';
        $record = new model_attendance_attendancerecord();
        switch ($typesof) {
            case 'time':

                if (in_array($dayse, array('seven', 'week', 'month'))) {
                    $group .= 'FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%m-%d")';
                    $field .= ',FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%m-%d") dayc';
                } else {
                    if (is_array($datime)) {
                        $group .= 'FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%Y-%m-%d")';
                        $field .= ',FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%Y-%m-%e") months';
                    } else {
                        $group .= 'FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%m")';
                        $field .= ',FROM_UNIXTIME(unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime)),"%m") months';
                    }
                }
                break;
            case 'company':
                $group .= 'mb.unitId';
                $field .= ',mb.unitId';
                break;
        }

        $stat_sort = self::array_structure($dayse);
        switch ($dayse) {
            case 'seven':
                $condition .= ' and unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))> ' . strtotime('-6 days') . ' and ' . strtotime(date('Y-m-d') . ' 23:59:59') . ' >unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))';
                break;
            case 'week':
                $on_monday = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)); //周一
                $Sunday = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600)); // 周日
                $condition .= ' and unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))> ' . strtotime($on_monday . ' 00:00:01') . ' and ' . strtotime($Sunday . ' 23:59:59') . ' >unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))';

                break;
            case 'month':
                $end_month = date('t');
                $dates = date('Y-m-');
                $on_monday = $dates . '01';
                $condition .= ' and unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))> ' . strtotime($dates . '01 00:00:01') . ' and ' . strtotime($dates . $end_month . ' 23:59:59') . ' >unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))';


                break;

            default:
                if (is_array($datime)) {
                    $condition .= ' and unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))> ' . strtotime($datime[0] . ' 00:00:01') . ' and ' . strtotime($datime[1] . ' 23:59:59') . ' >unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))';
                    $stat_sort = self::time_cal($datime[0], $datime[1]);
                } else {
                    $condition .= ' and unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))> ' . strtotime($datime . '-01-01 00:00:01') . ' and ' . strtotime($datime . '-12-31 23:59:59') . ' >unix_timestamp(CONCAT(atdc_attendance_record.sureDate,\' \',atdc_attendance_record.sureTime))';
                }
        }

        try {
            $member = new model_attendance_member();
            $res = $record->select($condition, $field, '', $group, array($member->tableName() . ' mb' => $record->tableName() . '.memberId=mb.id'))->items;

            //	$result->message = json_encode($record);
            $res = self::statConver($res, $stat_sort, $typesof, $dayse, $datime,$platformId,$adminUserId);
            if ($res) {
                $result->code = 200;
            } else {
                $result->code = 400;
            }


            $result->data = $res;
            //$result->message = json_encode($res);
            $result->success = true;
            return $result;
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage();
        }
        return $result;
    }

    /**
     * 考勤请假统计
     * @param AdminStatisticsDTO $AdminStatisticsDTO
     * @return ResultDO
     */
    public function getStatisticsLeave(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? $AdminStatisticsDTO->data :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $adminUserId = isset($data['adminUserId'])?$data['adminUserId']:0;
        $unitId = isset($data['unitId'])?$data['unitId']:0;
        $type = isset($data['type'])?$data['type']:1;
        $data2 = isset($data['data2'])?unserialize($data['data2']):[];

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        try{
//            获取这个平台管理员的请假统计
            $userModel = new service_user();
            $memberModel = new model_attendance_member();
            $leaveRecordModel = new model_attendance_approvalprocessleaverecord();

            $UnitsList = $userModel->getMemberUnitsRelation($platformId,$adminUserId,2);

            if ($type==1){
                $con = "  {$leaveRecordModel->tableName()}.platformId={$platformId}  and {$leaveRecordModel->tableName()}.status=2 ";
                if ($UnitsList['relation']){
                    $unitIds = array_column($UnitsList['relation'],'id');
                    $unitIds = implode(',',$unitIds);
                    $con.=" and at.unitId in ({$unitIds}) ";
                }else{
                    $con.=" and at.unitId={$unitId} ";
                }
                $join = array("atdc_member at"=>"at.id={$leaveRecordModel->tableName()}.memberId");
                $row = $leaveRecordModel->select($con," {$leaveRecordModel->tableName()}.leaveType,count({$leaveRecordModel->tableName()}.id) num "," group by {$leaveRecordModel->tableName()}.leaveType","",$join)->items;

                if ($row){//请假类型 默认为0 1 年假 2 事假 3 调休 4 产假 5 婚假 6 丧假 7 护理假 8病假 9产假
                    //["年假", "事假", "病假", "婚假", "产假"];
                    foreach ($row as $key=>$value){
                        switch ($value['leaveType']){
                            case 1:
                                $data2[0]['value'] = $value['num'];
                                break;
                            case 2:
                                $data2[1]['value'] = $value['num'];
                                break;
                            case 8:
                                $data2[2]['value'] = $value['num'];
                                break;
                            case 5:
                                $data2[3]['value'] = $value['num'];
                                break;
                            case 9:
                                $data2[4]['value'] = $value['num'];
                                break;
                        }
                    }
                }
                $result->data = $data2;
                $result->message ='成功';
                $result->code = 200;
            }else{
                $con = "  {$memberModel->tableName()}.platformId={$platformId}   and at.status=2 ";
                if ($UnitsList['relation']){
                    $unitIds = array_column($UnitsList['relation'],'id');
                    $unitIds = implode(',',$unitIds);
                    $con.=" and {$memberModel->tableName()}.unitId in ({$unitIds}) ";
                }else{
                    $con.=" and {$memberModel->tableName()}.unitId={$unitId} ";
                }
                $join = array("atdc_approval_process_leave_record at"=>"at.memberId={$memberModel->tableName()}.id");
                $memberList = $memberModel->select(
                    $con,
                    "{$memberModel->tableName()}.id,{$memberModel->tableName()}.userName,{$memberModel->tableName()}.realName,count(at.id) num",
                    " group by {$memberModel->tableName()}.id order by   count(at.id) desc  limit 5",
                    "",$join
                )->items;
                $data1 = [];
                $data2 = [];
                foreach ($memberList as $key=>$value){
                    $data1[] = $value['realName'];
                    $data2[] = $value['num'];
                }
                $result->data = [$data1,$data2];
                $result->message ='成功';
                $result->code = 200;
            }


        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }

    /**
     * 最新实时考勤
     * @param AdminStatisticsDTO $AdminStatisticsDTO
     * @return ResultDO
     */
    public function getStatisticsNewClockin(AdminStatisticsDTO $AdminStatisticsDTO){

        $data = $AdminStatisticsDTO->data ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->data) :[];
        $platformId = $AdminStatisticsDTO->platformId ? gdl_lib_BaseUtils::getStr($AdminStatisticsDTO->platformId) :0;

        #接受参数

        $adminUserId = $data['adminUserId']?$data['adminUserId']:0;
        $unitId = $data['unitId']?$data['unitId']:0;

        $result = new ResultDO();
        $result->success = true;
        $result->code = 400;
        $result->counts = 0;
        if(empty($platformId)){$result->message = "参数不正确"; return $result;}

        try{
            $userStatisticsInfos = [];
            $userModel = new service_user();
            $memberModel = new model_attendance_member();

            $UnitsList = $userModel->getMemberUnitsRelation($platformId,$adminUserId,2);
            $attendancerecordModel            = new model_attendance_attendancerecord();
            $con = " {$attendancerecordModel->tableName()}.platformId = {$platformId} and am.status = 2 ";
            if ($UnitsList['relation']){
                $unitIds = array_column($UnitsList['relation'],'id');
                $unitIds = implode(',',$unitIds);
                $con.=" and am.unitId in ({$unitIds}) ";
            }else{
                $con.=" and am.unitId={$unitId} ";
            }
            $join = array("atdc_member am"=>"{$attendancerecordModel->tableName()}.memberId=am.id");
            $memList = $attendancerecordModel->select(
                $con,
                "am.id,am.realName,am.photo,FROM_UNIXTIME({$attendancerecordModel->tableName()}.clockinTime) `date`,no,isGo,abnormal,abnormalCoordinateIs,abnormalIdentityIs,absenteeism,{$attendancerecordModel->tableName()}.clockinType,{$attendancerecordModel->tableName()}.clockinCoordinate",
                " order by {$attendancerecordModel->tableName()}.id desc  limit 5","",$join)->items;

            foreach ($memList as &$val){
                if (($val['abnormal']==0 && $val['absenteeism']==0 && $val['no']==1) || ($val['no']==3 and $val['isGo']==2)){
                    $val['no'] = 1;
                }else{
                    $val['no'] = 2;
                }
            }
            $result->data = $memList;
            $result->message ='成功';
            $result->code = 200;
        }catch(Exception $e){
            $result->code = 400;
            $result->message = '异常';
        }

        return $result;
    }

    /**
     * 通过不同参数返回不同的数据结构的起始数组
     */
    public function array_structure($dayse)
    {
        $stat_sort = ['nums' => [
            '1' => 0,
            '2' => 0,
            '3' => 0,
            '4' => 0,
            '5' => 0,
            '6' => 0,
            '7' => 0,
            '8' => 0,
            '9' => 0,
            '10' => 0,
            '11' => 0,
            '12' => 0,
        ],
            'times' => ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        ];
        switch ($dayse) {
            case 'seven':

                $stat_sort = ['nums' => [
                    date('m-d', strtotime('-6 days')) => 0,
                    date('m-d', strtotime('-5 days')) => 0,
                    date('m-d', strtotime('-4 days')) => 0,
                    date('m-d', strtotime('-3 days')) => 0,
                    date('m-d', strtotime('-2 days')) => 0,
                    date('m-d', strtotime('-1 days')) => 0,
                    date('m-d') => 0,
                ],
                    'times' => [date('Y-m-j', strtotime('-6 days')), date('Y-m-j', strtotime('-5 days')), date('Y-m-j', strtotime('-4 days')), date('Y-m-j', strtotime('-3 days')), date('Y-m-j', strtotime('-2 days')), date('Y-m-j', strtotime('-1 days')), date('Y-m-j')],
                ];
                break;
            case 'week':
                $on_monday = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)); //周一
                $on_mondays = strtotime($on_monday);
                $stat_sort = ['nums' => [
                    date('m-d', $on_mondays) => 0,
                    date('m-d', strtotime("+1 day", $on_mondays)) => 0,
                    date('m-d', strtotime("+2 day", $on_mondays)) => 0,
                    date('m-d', strtotime("+3 day", $on_mondays)) => 0,
                    date('m-d', strtotime("+4 day", $on_mondays)) => 0,
                    date('m-d', strtotime("+5 day", $on_mondays)) => 0,
                    date('m-d', strtotime("+6 day", $on_mondays)) => 0,
                ],
                    'times' => ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
                ];
                break;
            case 'month':
                $end_month = date('t');
                $dates = date('Y-m-');
                $on_monday = $dates . '01';
                $stat_sort = array();
                $months = date('m');
                for ($i = 0; $i < $end_month; $i++) {
                    $stat_sort['nums'][date('m-d', strtotime("+" . $i . " day", strtotime($on_monday)))] = 0;
                    $stat_sort['times'][] = $months . '-' . ($i + 1);
                }
                break;
        }
        return $stat_sort;
    }

    /**
    * 通过日期相差天数计算出 每天的日期
    */
    public function time_cal($starttime, $entime)
    {
        /*         * 获取他们相差天数* */
        $second1 = strtotime($starttime);
        $second2 = strtotime($entime);
        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        $dif_days = ($second1 - $second2) / 86400; //计算出相差天数
        $datatime = [];
        $starttime = date('Y-m-j', strtotime($starttime));
        if ($dif_days < 1) {

            $datatime['nums'][$starttime] = 0;
            // $datatime['times'][] = $starttime;
            $datatime['times'][] = date('Y-m-j', strtotime($starttime));
        } else {
            $datatime['nums'][$starttime] = 0;
            //$datatime['times'][] = $starttime ;
            $datatime['times'][] = date('Y-m-j', strtotime($starttime));
            for ($i = 1; $i <= $dif_days; $i++) {
                $dates = date('Y-m-j', strtotime("$starttime +" . $i . " day"));
                $datatime['nums'][$dates] = 0;
                $datatime['times'][] = $dates;
            }
        }
        return $datatime;
    }

    /**
     * $statConver 统计结果计算
     * $StatArr结果
     * $typesof 类型
     * $stat_sort 需要按什么数组计算
     */

    public function statConver($StatArr, $stat_sort, $typesof, $dayse, $datime,$platformId,$adminUserId)
    {
        $arr = [];
        $dates = 1;

        switch ($typesof) {
            case 'time':
                if (in_array($dayse, array('seven', 'week', 'month'))) {
                    foreach ($StatArr as $v) {
                        $dates = (int) $v['dayc'];

                        $stat_sort['nums'][$v['dayc']] = $v['nums'];
                    }
                } else {

                    if (is_array($datime)) {
                        foreach ($StatArr as $v) {

                            $dates = $v['months'];
                            //$stat_sort[$dates]["nums"] = $v['nums'];
                            $stat_sort['nums'][$dates] = $v['nums'];
                        }
                    } else {
                        foreach ($StatArr as $v) {

                            $dates = (int) $v['months'];
                            //$stat_sort[$dates]["nums"] = $v['nums'];
                            $stat_sort['nums'][$dates] = $v['nums'];
                        }
                    }
                }

                break;
            case 'company':
                $stat_sort = [];
                foreach ($StatArr as $v) {
                    $arr[] = $v['unitId'];
                }
//                 $units           = new model_lhbase_units();
                $serviceUserModel = new service_user();
                //获取当前平台的组织架构和考勤用户的关联数组
                $UnitsList = $serviceUserModel->getMemberUnitsRelation($platformId,$adminUserId,2);

//                $unitName = $units->select('id in(' . implode(',', $arr) . ')', 'id,unitName name', '', 'order by id desc')->items;
//                print_r($UnitsList);die;
                foreach ($UnitsList['relation'] as $pv) {
                    $stat_sort['nums'][$pv['id']] = 0;
                    $stat_sort['times'][] = $pv['title'];
                }

                foreach ($StatArr as $vs) {

                    if (isset($stat_sort['nums'][$vs['unitId']])) {
                        $stat_sort['nums'][$vs['unitId']] = $vs['nums'];
                    }
                }

                break;
        }
        $Reorganizationsa = [];

        foreach ($stat_sort as $bv) {
            if (!empty($bv)) {
                $Reorganizations = [];
                foreach ($bv as $v) {
                    $Reorganizations[] = $v;
                }
                $Reorganizationsa[] = $Reorganizations;
            }
        }


        return $Reorganizationsa;
    }
}
